//
//  PTCommonWebViewController.m
//  PersonalTaxProject
//
//  Created by 中税网 on 2019/3/9.
//  Copyright © 2019 TaxChina. All rights reserved.
//

#import "PTCommonWebViewController.h"
#import <WebKit/WebKit.h>
#import <MGFaceIDLiveDetect/MGFaceIDLiveDetect.h>
#import "Toast.h"
#import "MBProgressHUD.h"
#import <AVFoundation/AVFoundation.h>
#import "UIView+RMAdditions.h"
#import "PTCommonModel.h"
#import "MJExtension.h"
#import <AFNetworking/AFNetworking.h>

#import <CoreTelephony/CTCellularData.h>
#import "CEHeader.h"
#import "CustomeUpdateView.h"

#import "WSLScanView.h"
#import "WSLNativeScanTool.h"

@interface PTCommonWebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIDocumentInteractionControllerDelegate,AVCaptureMetadataOutputObjectsDelegate>{
    
    
    AVCaptureDevice *_videoDevice;
    AVCaptureDevice *_audioDevice;
    AVCaptureDeviceInput *_videoInput;
    AVCaptureDeviceInput *_audioInput;
    AVCaptureMovieFileOutput *_movieOutput;
    
    
    NSString * _authType;
    NSString * _examId;
    NSString * _questionId;
    

    
}



@property(nonatomic,strong) WKWebView * wkWebView ;

@property(nonatomic,assign)BOOL isShowRightNavigationButton ;

@property(nonatomic,strong)NSArray * dataArray ;

@property(nonatomic,strong)UIView * videoView ;

@property(nonatomic,strong)PTCommonModel * commonDataModel;

@property(nonatomic,strong)UIDocumentInteractionController * docInterCtrl ;

@property(nonatomic,strong)CustomeUpdateView * customeUpdateView ;


@property(nonatomic,strong)AVCaptureSession *  captureSession;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer * captureVideoPreviewLayer;

@property(nonatomic,strong)UIView * scanPreview;
@property(nonatomic,strong)WSLScanView *  scanView ;
@property(nonatomic,strong)WSLNativeScanTool * scanTool ;
@end

@implementation PTCommonWebViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self updateUserAppRequest];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.webUrlString = kWebBaseURL ; 

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    [configuration.userContentController addScriptMessageHandler:self name:@"callIos"];
    [configuration.userContentController addScriptMessageHandler:self name:@"callIosVideo"];
    [configuration.userContentController addScriptMessageHandler:self name:@"callIosTakePicture"];
    [configuration.userContentController addScriptMessageHandler:self name:@"downloadInvoiceAttachment"];
    [configuration.userContentController addScriptMessageHandler:self name:@"callIosScanCode"];//调用系统扫码二维码功能

    configuration.allowsInlineMediaPlayback = YES;
    WKWebView * webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kStatusBarHeight, kScreenWidth, kScreenHeight-kStatusBarHeight) configuration:configuration];
    webView.navigationDelegate = self;
    webView.UIDelegate  = self;
    [webView setCustomUserAgent:@"native_ios"];
    NSURL *url = [NSURL URLWithString:self.webUrlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:10.f];
    [webView loadRequest:request];
    self.wkWebView = webView;
    [self.view addSubview:  self.wkWebView];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSLog(@"userAgent :%@", result);
    }];
    [self.wkWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    [self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  
    
    self.videoView.hidden = YES;
    [self.view addSubview:self.videoView];
    self.commonDataModel = [[PTCommonModel alloc] init];
    
    CTCellularData *cellularData = [[CTCellularData alloc]init];
    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state){
        //状态改变时进行相关操作

        if (state == kCTCellularDataNotRestricted) {
//             NSLog(@"reloadWebView");
            [self performSelectorOnMainThread:@selector(reloadWebView) withObject:nil waitUntilDone:NO];
        }

    };

}
-(void)reloadWebView{
        [self.wkWebView reload];
}





#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{

    //    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    if ([message.name isEqualToString:@"callIos"]) {
        NSLog(@"body:%@",message.body);
        NSDictionary * dict = message.body;
        self.commonDataModel.biz_token = [dict objectForKey:@"biz_token"];
        self.commonDataModel.examId = [dict objectForKey:@"examId"];
        self.commonDataModel.questionId = [dict objectForKey:@"questionId"];
        self.commonDataModel.authType = [dict objectForKey:@"authType"];
        self.commonDataModel.from = [dict objectForKey:@"from"];
        self.commonDataModel.userCreditId = [dict objectForKey:@"userCreditId"];
        self.commonDataModel.qrType = [dict objectForKey:@"qrType"];
        self.commonDataModel.uuid = [dict objectForKey:@"uuid"];
        [self startFaceDetect];
     
    }else if ([message.name isEqualToString:@"callIosVideo"]){
        NSLog(@"body:%@",message.body);
        if ([[message.body objectForKey:@"action"] isEqualToString:@"open"]) {
            [self getAuthorization];
        }else{
            self.videoView.hidden = YES ;
             [_captureSession stopRunning];
        }
    }else if ([message.name isEqualToString:@"callIosTakePicture"]){
        [self showImagePickerForSourceType:UIImagePickerControllerSourceTypeCamera andCameraCaptureMode:UIImagePickerControllerCameraCaptureModePhoto];

    }else if ([message.name isEqualToString:@"downloadInvoiceAttachment"]){
        NSString * fileName = message.body[@"fileName"];
        NSString * downUrl = message.body[@"downUrl"];
        [self downloadFileWithUrl:downUrl fileName:fileName];

    }else if ([message.name isEqualToString:@"callIosScanCode"]){//调用手机扫二维码功能
        NSLog(@"body:%@",message.body);
//        [self startQrCodeScanning];
        [self startScanQrCode];
    }
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
  
//   UIImagePickerController
    
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    //    显示h5界面的title
    if(object == self.wkWebView && [keyPath isEqualToString:@"title"]){
        self.title = self.wkWebView.title;
    }else if (object == self.wkWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
         
            //            [self loaddingSuccess];
        }else {
            //            [self showGifLoading];
        }
    }else{
        
    }
}


- (void)dealloc {
    //记得移除
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.wkWebView removeObserver:self forKeyPath:@"title"];
    
}
#pragma mark - showCheckMessage
- (void)showCheckMessage:(NSString *)checkMessage {
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = checkMessage;
        [hud hideAnimated:YES afterDelay:2];
    });
}
#pragma mark - 开始人脸识别验证
-(void)startFaceDetect {
    MGFaceIDLiveDetectError* error;
    NSString * bizToken = self.commonDataModel.biz_token;
    MGFaceIDLiveDetectManager* detectManager = [[MGFaceIDLiveDetectManager alloc] initMGFaceIDLiveDetectManagerWithBizToken:bizToken language:MGFaceIDLiveDetectLanguageCh  networkHost:@"https://api.megvii.com"   extraData:nil error:&error];
    if (error || !detectManager) {
        [self.view makeToast:error.errorMessageStr duration:2 position:CSToastPositionCenter];
    }
    
    [detectManager startMGFaceIDLiveDetectWithCurrentController:self
                                                       callback:^(MGFaceIDLiveDetectError *error, NSData *deltaData, NSString *bizTokenStr, NSDictionary *extraOutDataDict) {
                                                           NSLog(@"%@=====",error);
                                                            self.commonDataModel.errorType = [NSString stringWithFormat:@"%lu",(unsigned long)error.errorType];
                                                           if (error.errorType == MGFaceIDLiveDetectErrorNone) {
                                                               NSString * dataString = [[NSString alloc] initWithData:deltaData encoding:NSUTF8StringEncoding];
                                                               self.commonDataModel.megLiveData = dataString;
                                                               self.commonDataModel.errorMessage = @"";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorIllegalParameter){
                                                               self.commonDataModel.errorMessage = @"传入的参数不合法";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorBizTokenDenied){
                                                               self.commonDataModel.errorMessage = @"传入的biz_token不符合要求";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorAuthenticationFail){
                                                               self.commonDataModel.errorMessage = @"鉴权失败";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorMobilePhoneNotSupport){
                                                               self.commonDataModel.errorMessage = @"手机不在支持列表里";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorSDKTooOld){
                                                               self.commonDataModel.errorMessage = @"SDK版本过旧，已经不被支持";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorUserCancel){
                                                               self.commonDataModel.errorMessage = @"用户取消活体检测";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorNotResource){
                                                               self.commonDataModel.errorMessage = @"未添加资源包";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorNotCameraPermission){
                                                               self.commonDataModel.errorMessage = @"APP没有获取相机权限";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorNotCameraSupport){
                                                               self.commonDataModel.errorMessage = @"APP未找到可用的相机设备";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorFaceInitFail){
                                                               self.commonDataModel.errorMessage = @"活体检测启动失败";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorNetWorkNotConnected){
                                                               self.commonDataModel.errorMessage = @"连不上互联网，请检查网络连接状态";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorOnvalidBundleID){
                                                               self.commonDataModel.errorMessage = @"APP信息验证失败";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorBackGround){
                                                               self.commonDataModel.errorMessage = @"活体检测阶段因APP进入后台导致检测失败";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorLiveFail){
                                                               self.commonDataModel.errorMessage = @"活体检测失败";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorUnknown){
                                                               self.commonDataModel.errorMessage = @"未知错误";
                                                           }else if (error.errorType == MGFaceIDLiveDetectErrorTimeOut){
                                                               self.commonDataModel.errorMessage = @"操作超时";
                                                           }
                                                          
                                                            [self callH5Wap];

                                                       }];
}

#pragma mark - 人脸识别验证后回调h5
-(void)callH5Wap{
    NSString *jsStr = self.commonDataModel.mj_JSONString;
    NSString * jsString = [NSString stringWithFormat:@"callWap('%@')",jsStr];

    NSLog(@"网页地址：==%@,js语句：==%@",self.webUrlString,jsStr);
    [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
}

#pragma mark - 下载发票文件
-(void)downloadFileWithUrl:(NSString *)urlString  fileName:(NSString *)fileName{
    if (!urlString || !fileName || urlString.length ==0 || fileName.length ==0) {
        return;
    }
    /* 创建网络下载对象 */
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    /* 下载地址 */
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    /* 下载路径 */
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    NSString *path = [cachPath stringByAppendingPathComponent:@"invoiceFiles"];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSString *dir = [filePath stringByDeletingLastPathComponent];
        [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    /* 开始请求下载 */
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //如果需要进行UI操作，需要获取主线程进行操作
        });
        /* 设定下载到的位置 */
        return [NSURL fileURLWithPath:filePath];
                
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
         NSLog(@"下载完成 filePath===%@ downloadUrl===%@",filePath,urlString);
        [self handleDownloadFinishedWithFilePath:filePath error:error];

    }];
     [downloadTask resume];

}

-(void)handleDownloadFinishedWithFilePath:(NSURL *)filePath  error:(NSError *)error{
     if (error  == nil) {
        [self setupDocumentControllerWithURL:filePath];
        BOOL ret = [self.docInterCtrl presentOpenInMenuFromRect:self.view.bounds inView:self.view  animated:YES];
        if (!ret) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"暂无可打开该文件的应用" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"  style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                                    
            }];
        [alertController addAction:cancelAction];
                                
        [self presentViewController:alertController animated:YES completion:nil];
        }

    }else{
        NSLog(@"no finished error==%@", error.description);
    }
}


- (void)setupDocumentControllerWithURL:(NSURL *)url
{
    if (self.docInterCtrl == nil) {
        self.docInterCtrl =
        [UIDocumentInteractionController interactionControllerWithURL:url];
        self.docInterCtrl.delegate = self;
    } else {
        self.docInterCtrl.URL = url;
    }
}

-(AVCaptureSession *)captureSession{
    if (!_captureSession) {
        _captureSession = [[AVCaptureSession alloc] init];
    }
    return _captureSession;
}
- (AVCaptureVideoPreviewLayer *)captureVideoPreviewLayer{
    if (!_captureVideoPreviewLayer) {
        _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
    }
    return _captureVideoPreviewLayer;
}


- (UIView *)videoView{
    if (_videoView == nil) {
        _videoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
        //添加移动的手势
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanGesture:)];
        pan.delaysTouchesBegan = YES;
        [_videoView addGestureRecognizer:pan];

    }
    return _videoView;
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)recognizer
{
    //移动状态
    UIGestureRecognizerState recState =  recognizer.state;

    switch (recState) {
        case UIGestureRecognizerStateBegan:

            break;
        case UIGestureRecognizerStateChanged:
        {
            CGPoint translation = [recognizer translationInView:self.navigationController.view];
            recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            CGPoint stopPoint = CGPointMake(0,kScreenHeight / 2.0);

            if (recognizer.view.center.x < kScreenWidth / 2.0) {
                if (recognizer.view.center.y <= kScreenHeight/2.0) {
                    //左上
                    if (recognizer.view.center.x  >= recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, self.videoView.width/2.0);
                    }else{
                        stopPoint = CGPointMake(self.videoView.width/2.0, recognizer.view.center.y);
                    }
                }else{
                    //左下
                    if (recognizer.view.center.x  >= kScreenHeight - recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, kScreenHeight - self.videoView.width/2.0);
                    }else{
                        stopPoint = CGPointMake(self.videoView.width/2.0, recognizer.view.center.y);
                        //                        stopPoint = CGPointMake(recognizer.view.center.x, SCREEN_HEIGHT - self.spButton.width/2.0);
                    }
                }
            }else{
                if (recognizer.view.center.y <= kScreenHeight/2.0) {
                    //右上
                    if (kScreenWidth - recognizer.view.center.x  >= recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, self.videoView.width/2.0);
                    }else{
                        stopPoint = CGPointMake(kScreenWidth - self.videoView.width/2.0, recognizer.view.center.y);
                    }
                }else{
                    //右下
                    if (SCREEN_WIDTH - recognizer.view.center.x  >= kScreenHeight - recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, kScreenHeight - self.videoView.width/2.0);
                    }else{
                        stopPoint = CGPointMake(kScreenWidth - self.videoView.width/2.0,recognizer.view.center.y);
                    }
                }
            }

            //如果按钮超出屏幕边缘
            if (stopPoint.y + self.videoView.width+40>= kScreenHeight) {
                stopPoint = CGPointMake(stopPoint.x, kScreenHeight - self.videoView.width/2.0-49);
                NSLog(@"超出屏幕下方了！！"); //这里注意iphoneX的适配。。X的SCREEN高度算法有变化。
            }
            if (stopPoint.x - self.videoView.width/2.0 <= 0) {
                stopPoint = CGPointMake(self.videoView.width/2.0, stopPoint.y);
            }
            if (stopPoint.x + self.videoView.width/2.0 >= SCREEN_WIDTH) {
                stopPoint = CGPointMake(kScreenWidth - self.videoView.width/2.0, stopPoint.y);
            }
            if (stopPoint.y - self.videoView.width/2.0 <= 0) {
                stopPoint = CGPointMake(stopPoint.x, self.videoView.width/2.0);
            }

            [UIView animateWithDuration:0.5 animations:^{
                recognizer.view.center = stopPoint;
            }];
        }
            break;

        default:
            break;
    }

    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}


//获取授权
- (void)getAuthorization
{
    /*
     AVAuthorizationStatusNotDetermined = 0,// 未进行授权选择
     
     AVAuthorizationStatusRestricted,　　　　// 未授权，且用户无法更新，如家长控制情况下
     
     AVAuthorizationStatusDenied,　　　　　　 // 用户拒绝App使用
     
     AVAuthorizationStatusAuthorized,　　　　// 已授权，可使用
     */
    //此处获取摄像头授权
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo])
    {
        case AVAuthorizationStatusAuthorized:       //已授权，可使用    The client is authorized to access the hardware supporting a media type.
        {
            NSLog(@"授权摄像头使用成功");
            [self setupAVCaptureInfo];
            break;
        }
        case AVAuthorizationStatusNotDetermined:    //未进行授权选择     Indicates that the user has not yet made a choice regarding whether the client can access the hardware.
        {
            //则再次请求授权
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if(granted){    //用户授权成功
                    [self setupAVCaptureInfo];
                    return;
                } else {        //用户拒绝授权
                    [self.view makeToast:@"用户拒绝授权摄像头的使用权,返回上一页.请打开\n设置-->隐私/通用等权限设置" duration:2 position:CSToastPositionCenter];
                    return;
                }
            }];
            break;
        }
        default:                                    //用户拒绝授权/未授权
        {
            [self.view makeToast:@"拒绝授权,返回上一页.请检查下\n设置-->隐私/通用等权限设置" duration:2 position:CSToastPositionCenter];
            break;
        }
    }
    
}


- (void)setupAVCaptureInfo
{
    [self addSession];
    
    [_captureSession beginConfiguration];
    
    [self addVideo];
    [self addAudio];
    [self addPreviewLayer];
    
    [_captureSession commitConfiguration];
    
    //开启会话-->注意,不等于开始录制
    [_captureSession startRunning];
    
}

- (void)addSession
{
    _captureSession = [[AVCaptureSession alloc] init];
    //设置视频分辨率
    /*  通常支持如下格式
     (
     AVAssetExportPresetLowQuality,
     AVAssetExportPreset960x540,
     AVAssetExportPreset640x480,
     AVAssetExportPresetMediumQuality,
     AVAssetExportPreset1920x1080,
     AVAssetExportPreset1280x720,
     AVAssetExportPresetHighestQuality,
     AVAssetExportPresetAppleM4A
     )
     */
    //注意,这个地方设置的模式/分辨率大小将影响你后面拍摄照片/视频的大小,
    if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset640x480]) {
        [_captureSession setSessionPreset:AVCaptureSessionPreset640x480];
    }
}

- (void)addVideo
{
    // 获取摄像头输入设备， 创建 AVCaptureDeviceInput 对象
    /* MediaType
     AVF_EXPORT NSString *const AVMediaTypeVideo                 NS_AVAILABLE(10_7, 4_0);       //视频
     AVF_EXPORT NSString *const AVMediaTypeAudio                 NS_AVAILABLE(10_7, 4_0);       //音频
     AVF_EXPORT NSString *const AVMediaTypeText                  NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeClosedCaption         NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeSubtitle              NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeTimecode              NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeMetadata              NS_AVAILABLE(10_8, 6_0);
     AVF_EXPORT NSString *const AVMediaTypeMuxed                 NS_AVAILABLE(10_7, 4_0);
     */
    
    /* AVCaptureDevicePosition
     typedef NS_ENUM(NSInteger, AVCaptureDevicePosition) {
     AVCaptureDevicePositionUnspecified         = 0,
     AVCaptureDevicePositionBack                = 1,            //后置摄像头
     AVCaptureDevicePositionFront               = 2             //前置摄像头
     } NS_AVAILABLE(10_7, 4_0) __TVOS_PROHIBITED;
     */
    _videoDevice = [self deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionFront];
    
    [self addVideoInput];
    [self addMovieOutput];
}

- (void)addVideoInput
{
    NSError *videoError;
    
    // 视频输入对象
    // 根据输入设备初始化输入对象，用户获取输入数据
    _videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:_videoDevice error:&videoError];
    if (videoError) {
        NSLog(@"---- 取得摄像头设备时出错 ------ %@",videoError);
        return;
    }
    
    // 将视频输入对象添加到会话 (AVCaptureSession) 中
    if ([_captureSession canAddInput:_videoInput]) {
        [_captureSession addInput:_videoInput];
    }
    
}

- (void)addMovieOutput
{
    // 拍摄视频输出对象
    // 初始化输出设备对象，用户获取输出数据
    _movieOutput = [[AVCaptureMovieFileOutput alloc] init];
    
    if ([_captureSession canAddOutput:_movieOutput]) {
        [_captureSession addOutput:_movieOutput];
        AVCaptureConnection *captureConnection = [_movieOutput connectionWithMediaType:AVMediaTypeVideo];
        
        //设置视频旋转方向
        /*
         typedef NS_ENUM(NSInteger, AVCaptureVideoOrientation) {
         AVCaptureVideoOrientationPortrait           = 1,
         AVCaptureVideoOrientationPortraitUpsideDown = 2,
         AVCaptureVideoOrientationLandscapeRight     = 3,
         AVCaptureVideoOrientationLandscapeLeft      = 4,
         } NS_AVAILABLE(10_7, 4_0) __TVOS_PROHIBITED;
         */
        //        if ([captureConnection isVideoOrientationSupported]) {
        //            [captureConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
        //        }
        
        // 视频稳定设置
        if ([captureConnection isVideoStabilizationSupported]) {
            captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
        }
        
        captureConnection.videoScaleAndCropFactor = captureConnection.videoMaxScaleAndCropFactor;
    }
    
}

- (void)addAudio
{
    NSError *audioError;
    // 添加一个音频输入设备
    _audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    //  音频输入对象
    _audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:_audioDevice error:&audioError];
    if (audioError) {
        NSLog(@"取得录音设备时出错 ------ %@",audioError);
        return;
    }
    // 将音频输入对象添加到会话 (AVCaptureSession) 中
    if ([_captureSession canAddInput:_audioInput]) {
        [_captureSession addInput:_audioInput];
    }
}

- (void)addPreviewLayer
{
    
    [self.view layoutIfNeeded];
    
    // 通过会话 (AVCaptureSession) 创建预览层
    _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    _captureVideoPreviewLayer.frame = self.videoView.layer.bounds;
    /* 填充模式
     Options are AVLayerVideoGravityResize, AVLayerVideoGravityResizeAspect and AVLayerVideoGravityResizeAspectFill. AVLayerVideoGravityResizeAspect is default.
     */
    //有时候需要拍摄完整屏幕大小的时候可以修改这个
    //    _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    // 如果预览图层和视频方向不一致,可以修改这个
    _captureVideoPreviewLayer.connection.videoOrientation = [_movieOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation;
    _captureVideoPreviewLayer.position = CGPointMake(self.videoView.width*0.5,self.videoView.height*0.5);
    
    // 显示在视图表面的图层
    self.videoView.hidden = NO;
    CALayer *layer = self.videoView.layer;
    layer.masksToBounds = true;
    [self.view layoutIfNeeded];
    [layer addSublayer:_captureVideoPreviewLayer];

}

#pragma mark 获取摄像头-->前/后

- (AVCaptureDevice *)deviceWithMediaType:(NSString *)mediaType preferringPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
    AVCaptureDevice *captureDevice = devices.firstObject;
    
    for ( AVCaptureDevice *device in devices ) {
        if ( device.position == position ) {
            captureDevice = device;
            break;
        }
    }
    
    return captureDevice;
}



- (void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType andCameraCaptureMode:(UIImagePickerControllerCameraCaptureMode)mode{
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    //这是 VC 的各种 modal 形式
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerController.sourceType = sourceType;
    //支持的摄制类型,拍照或摄影,此处将本设备支持的所有类型全部获取,并且同时赋值给imagePickerController的话,则可左右切换摄制模式
    imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    imagePickerController.delegate = self;
    //允许拍照后编辑
    imagePickerController.allowsEditing = YES;
    //显示默认相机 UI, 默认为yes--> 显示
    //    imagePickerController.showsCameraControls = NO;
    
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        //设置模式-->拍照/摄像
        imagePickerController.cameraCaptureMode = mode;
        //开启默认摄像头-->前置/后置
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        //设置默认的闪光灯模式-->开/关/自动
        imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        
        //拍摄时预览view的transform属性，可以实现旋转，缩放功能
        //        imagePickerController.cameraViewTransform = CGAffineTransformMakeRotation(M_PI);
        //        imagePickerController.cameraViewTransform = CGAffineTransformMakeScale(2.0,2.0);
        
        //自定义覆盖图层-->overlayview
//        UIImage *img = [UIImage imageNamed:@"085625KMV.jpg"];
//        UIImageView *iv = [[UIImageView alloc] initWithImage:img];
//        iv.width = 300;
//        iv.height = 200;
//        imagePickerController.cameraOverlayView = iv;
    }
    [self presentViewController:imagePickerController animated:YES completion:NULL];
}
#pragma mark delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]) {
//        NSLog(@"image...");
        
        /*
         //获取照片的原图
         UIImage* original = [info objectForKey:UIImagePickerControllerOriginalImage];
         //获取图片裁剪后，剩下的图
         UIImage* crop = [info objectForKey:UIImagePickerControllerCropRect];
         //获取图片的url
         NSURL* url = [info objectForKey:UIImagePickerControllerMediaURL];
         //获取图片的metadata数据信息
         NSDictionary* metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
         */
        
        //获取图片裁剪的图
        [picker dismissViewControllerAnimated:YES completion:^{
            UIImage* editImage = [info objectForKey:UIImagePickerControllerEditedImage];
            NSData * imageData = UIImagePNGRepresentation(editImage) ;
            NSString *image64 = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
            NSString * jsStr = [NSString stringWithFormat:@"callWapTakePicture('%@')",image64];
            
            NSLog(@"网页地址：=====%@,js语句：=====%@",self.webUrlString,jsStr);
            [self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                NSLog(@"%@----%@",result, error);
            }];
        }];
       
        
    }
//    else{  // public.movie
//        NSLog(@"video...");
//        NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];//视频路径
//        NSString *urlStr=[url path];
//
////        [self saveVideo:urlStr];
//    }
    
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    NSLog(@"取消");
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - 开始扫二维码
- (void)startQrCodeScanning{
    /**
     扫描二维码 大概的流程应该是：1.打开设备的摄像头-->2.进行二维码图像捕获-->3.获取捕获的图像进行解析-->4.取得解析结果进行后续的处理。这些流程需要用到AVFoundation这个库
     */

    /**
     上面完成了捕获的设置，但是并未正在开始'扫描'，要完成一次扫描的过程，需要用到AVCaptureSession这个类，这个session类把一次扫描看做一次会话，会话开始后才是正在的'扫描'开始,具体代码如下。
     */
    [self.captureSession setSessionPreset:AVCaptureSessionPresetHigh];//扫描的质量
    //获取摄像头设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    //拍完照片以后，需要一个AVCaptureMetadataOutput对象将获取的'图像'输出，以便进行对其解析
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc] init];

    if ([self.captureSession canAddInput:input]) {
        [self.captureSession addInput:input];
    }else{
        //出错处理
        NSLog(@"%@", error);
        return;
    }
    if ([self.captureSession canAddOutput:output]) {
        [self.captureSession addOutput:output];
    }
    //设置输出类型 有二维码 条形码等
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode  //二维码
                                   ];
    //获取输出需要设置代理，在代理方法中获取
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    /**
     接下来我们要做的不是立即开始会话(开始扫描)，如果你现在调用会话的startRunning方法的话，你会发现屏幕是一片黑，这时由于我们还没有设置相机的取景器的大小。设置取景器需要用到AVCaptureVideoPreviewLayer这个类。具体代码如下：
     */
    self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResize;
    [self.captureVideoPreviewLayer setFrame:self.view.bounds];//设置取景器的frame
    [self.view.layer insertSublayer:self.captureVideoPreviewLayer atIndex:0];
    self.wkWebView.hidden  = YES;
//    CGSize size = self.view.bounds.size;
//    CGSize transparentAreaSize = CGSizeMake(200,200);
//    CGRect cropRect = CGRectMake((size.width - transparentAreaSize.width)/2, (size.height - transparentAreaSize.height)/2, transparentAreaSize.width, transparentAreaSize.height);
//    output.rectOfInterest = CGRectMake(cropRect.origin.y/size.width,
//                                       cropRect.origin.x/size.height,
//                                       cropRect.size.height/size.height,
//                                       cropRect.size.width/size.width);

    output.rectOfInterest = CGRectMake((124)/[[UIScreen mainScreen] bounds].size.height,(([[UIScreen mainScreen] bounds].size.width-220)/2)/[[UIScreen mainScreen] bounds].size.width,220/[[UIScreen mainScreen] bounds].size.height,220/[[UIScreen mainScreen] bounds].size.width);
    //开始扫码
    [self.captureSession startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    [self.captureSession stopRunning];//停止会话
    [self.captureVideoPreviewLayer removeFromSuperlayer];//移除取景器
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject * obj = metadataObjects[0];
        NSString * result = obj.stringValue;//这就是扫描的结果
        NSLog(@"outPut result == %@",result);
//        二维码扫码出结果  回调h5
        NSString * jsString = [NSString stringWithFormat:@"callWapScanCode('%@')",result];
        NSLog(@"网页地址：==%@,js语句：==%@",self.webUrlString,result);
        [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            NSLog(@"%@----%@",result, error);
        }];
    }
}

-(void)startScanQrCode{
    //输出流视图
        self.scanPreview  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 0)];
        [self.view addSubview:self.scanPreview];
    
        __weak typeof(self) weakSelf = self;
        
        //构建扫描样式视图
        _scanView = [[WSLScanView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 0)];
        _scanView.scanRetangleRect = CGRectMake(60, (self.view.frame.size.height - (self.view.frame.size.width -2 * 60))/2, (self.view.frame.size.width - 2 * 60),  (self.view.frame.size.width - 2 * 60));
        _scanView.colorAngle = [UIColor colorWithRed:122/255.0 green:153/255.0 blue:239/255.0 alpha:1];
        _scanView.photoframeAngleW = 30;
        _scanView.photoframeAngleH = 30;
        _scanView.photoframeLineW = 4;
        _scanView.isNeedShowRetangle = YES;
        _scanView.colorRetangleLine = [UIColor colorWithRed:122/255.0 green:153/255.0 blue:239/255.0 alpha:1];
        _scanView.notRecoginitonArea = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
        _scanView.animationImage = [UIImage imageNamed:@"scanLine"];
//        _scanView.myQRCodeBlock = ^{
//         [WSLNativeScanTool createQRCodeImageWithString:@"https://www.jianshu.com/u/e15d1f644bea" andSize:CGSizeMake(250, 250) andBackColor:[UIColor whiteColor] andFrontColor:[UIColor orangeColor] andCenterImage:[UIImage imageNamed:@"piao"]];
////            createQRCodeController.qrString = @"https://www.jianshu.com/u/e15d1f644bea";
//        };
        _scanView.flashSwitchBlock = ^(BOOL open) {
            [weakSelf.scanTool openFlashSwitch:open];
        };
        [self.view addSubview:_scanView];
        
        //初始化扫描工具
        _scanTool = [[WSLNativeScanTool alloc] initWithPreview:self.scanPreview andScanFrame:_scanView.scanRetangleRect];
        _scanTool.scanFinishedBlock = ^(NSString *scanString) {
            NSLog(@"扫描结果 %@",scanString);
            [weakSelf.scanTool sessionStopRunning];
            [weakSelf.scanTool openFlashSwitch:NO];
            [weakSelf dismissScanView];
            //        二维码扫码出结果  回调h5
            NSString * jsString = [NSString stringWithFormat:@"callWapScanCode('%@')",scanString];
            NSLog(@"网页地址：==%@,js语句：==%@",weakSelf.webUrlString,jsString);
            [weakSelf.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                NSLog(@"%@----%@",result, error);
            }];
        };
        _scanTool.monitorLightBlock = ^(float brightness) {
//            NSLog(@"环境光感 ： %f",brightness);
            if (brightness < 0) {
                // 环境太暗，显示闪光灯开关按钮
                [weakSelf.scanView showFlashSwitch:YES];
            }else if(brightness > 0){
                // 环境亮度可以,且闪光灯处于关闭状态时，隐藏闪光灯开关
                if(!weakSelf.scanTool.flashOpen){
                    [weakSelf.scanView showFlashSwitch:NO];
                }
            }
        };
        [_scanTool sessionStartRunning];
        [_scanView startScanAnimation];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    btn.frame = CGRectMake(0, statusBarHeight, 50, 44);
    [btn setImage:[UIImage imageNamed:@"back_icon"] forState:0];
    [btn addTarget:self action:@selector(dismissScanView) forControlEvents:UIControlEventTouchUpInside];
    [self.scanView addSubview:btn];
}

-(void)dismissScanView{
    [self.scanTool sessionStopRunning];
    [self.scanView removeFromSuperview];
    [self.scanPreview removeFromSuperview];
}


-(CustomeUpdateView *)customeUpdateView{
    if (!_customeUpdateView) {
        _customeUpdateView = [[CustomeUpdateView alloc] init];
        [self.view.window addSubview:_customeUpdateView];
    }
    return _customeUpdateView;
}
-(void)updateUserAppRequest{
       /* 下载地址 */
    NSString * urlString = [NSString stringWithFormat:@"%@/api/upgrade/check",kApiBaseURL] ;
    NSString * appVersion = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
   //初始化一个AFHTTPSessionManager
   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   //设置请求体数据为json类型
   manager.requestSerializer = [AFJSONRequestSerializer serializer];
   //设置响应体数据为json类型
   manager.responseSerializer = [AFJSONResponseSerializer serializer];
   //请求体，参数（NSDictionary 类型）
   NSDictionary *parameters = @{@"type":@"ios",
                                @"version":appVersion
                                };

    NSDictionary * headerDict = @{};
    [manager GET:urlString parameters:parameters headers:headerDict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject====%@",responseObject);
        
        if ([[responseObject objectForKey:@"code"] integerValue]==0) {
            NSDictionary * dataDict = [responseObject objectForKey:@"data"];
            
            if ([[dataDict objectForKey:@"force"] integerValue]==1) {
                [self.customeUpdateView showUpdateView:[dataDict objectForKey:@"releaseNotes"] isForce:YES];
                self.customeUpdateView.updateBlock = ^(id  _Nonnull sender) {
                    NSURL * url = [NSURL URLWithString:[dataDict objectForKey:@"url"]];
                    [[UIApplication sharedApplication] openURL:url];
                    exit(0);
                };
            } else {
                NSString * currentOnlineVersion = [dataDict objectForKey:@"version"];
                if ([currentOnlineVersion compare:appVersion] ==NSOrderedDescending) {
                    NSLog(@"上架版本号%@===当前APP版本号%@  版本更新了",currentOnlineVersion,appVersion);
                    [self.customeUpdateView showUpdateView:[dataDict objectForKey:@"releaseNotes"] isForce:NO];
                    self.customeUpdateView.updateBlock = ^(id  _Nonnull sender) {
                        NSURL * url = [NSURL URLWithString:[dataDict objectForKey:@"url"]];
                        [[UIApplication sharedApplication] openURL:url];
                    };
                }
            }
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error===%@",error);
    }];

}


-(BOOL)compareVesionWithServerVersion:(NSString *)version   currentAppVersion:(NSString * )currentAppVersion{

    NSArray *versionArray = [version componentsSeparatedByString:@"."];//服务器返回版

    NSArray *currentVesionArray = [currentAppVersion componentsSeparatedByString:@"."];//当前版本

    NSInteger a = (versionArray.count> currentVesionArray.count)?currentVesionArray.count : versionArray.count;
    for (int i = 0; i< a; i++) {

    NSInteger a = [[versionArray objectAtIndex:i] integerValue];

    NSInteger b = [[currentVesionArray objectAtIndex:i] integerValue];

    if (a > b) {

        NSLog(@"有新版本");

        return YES;

    }else if(a < b){

        return NO;

    }

    return NO;

}
    return NO;
}







@end
